package news;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import database.AppDatabase;
import database.NewsDatabaseService;
import de.app.badresden.R;

public class NewsActivity extends Activity implements OnItemClickListener, OnCancelListener {

	private ProgressDialog progressdialog;
	private NewsDatabaseService dbService;
	private boolean internet;

	public void onCreate(Bundle icicle) {

		super.onCreate(icicle);

		dbService = new NewsDatabaseService(
				new AppDatabase(getApplicationContext()).getWritableDatabase());

		internet = getIntent().getExtras().getBoolean("HasInternet");

		if (internet) progressdialog = ProgressDialog.show(NewsActivity.this,
				getString(R.string.progressdialog_title),
				getString(R.string.progressdialog_news), true, true, this);
		else
			progressdialog = ProgressDialog.show(NewsActivity.this,
					getString(R.string.progressdialog_title),
					getString(R.string.progressdialog_database), true, true, this);

		Thread newsImportThread = new Thread() {

			public void run() {

				try {
					synchronized (this) {
						ArrayList<News> news;

						if (internet) {
							NewsImport newsImport = new NewsImport(getIntent().getExtras()
									.getString("cookievalue"));
							news = newsImport.GetNews(getString(R.string.url_news));
						}
						else {
							news = dbService.GetNews();
							Thread.sleep(5000);
						}

						Bundle bundle = new Bundle();
						bundle.putSerializable("news", (Serializable) news);
						Message msg = new Message();
						msg.setData(bundle);
						updateHandler.sendMessage(msg);
					}
				}
				catch (Exception e) {
					Log.d("badresden app", e.toString());
				}
			}
		};
		newsImportThread.start();
	}

	private Handler updateHandler = new Handler() {

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			super.handleMessage(msg);

			Bundle bundle = msg.getData();
			ArrayList<News> news = (ArrayList<News>) bundle.getSerializable("news");

			setContentView(R.layout.news_layout);
			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			if (preferences.getBoolean("save_data", false) && internet) {
				dbService.InsertNews(news);
			}

			createList(news);
			progressdialog.dismiss();
		}
	};

	private void createList(ArrayList<News> news) {

		if (news.isEmpty()) {
			Date date = new Date();
			Locale loc = getBaseContext().getResources().getConfiguration().locale;
			SimpleDateFormat dayformat = new SimpleDateFormat("dd.MM.yyyy", loc);
			News tmp = new News(dayformat.format(date), "", getString(R.string.news_nonews));
			news.add(tmp);
		}

		ArrayAdapter<News> listViewAdapter = new NewsArrayAdapter(this, news);
		Collections.sort(news, new NewsSortByDate());

		ListView listView = (ListView) findViewById(R.id.news_listview);
		listView.setOnItemClickListener(this);
		listView.setAdapter(listViewAdapter);
	}

	@Override
	public void onItemClick(AdapterView<?> l, View v, int position, long id) {

		News news = (News) l.getAdapter().getItem(position);

		Intent intent = new Intent();
		Bundle bun = new Bundle();

		bun.putSerializable("News", (Serializable) news);

		intent.setClass(this, NewsDetailsActivity.class);
		intent.putExtras(bun);
		startActivity(intent);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		dbService.close();
	}

	@Override
	public void onCancel(DialogInterface dialog) {
		progressdialog.dismiss();
		finish();
	}
}
